<template>
  <div class="red-book-form">
    <a-form
      layout="vertical"
      :rules="rules"
    >
      <a-form-item label="封面" name="poster" v-bind="validateInfos.poster">
        <a-radio-group name="radioGroup" v-model:value="formRef.poster_access">
          <a-radio value="1">自动 
            <a-tooltip placement="topLeft">
                <template #title>
                  <span>自动从文章中摘取</span>
                </template>
                <QuestionCircleOutlined />
              </a-tooltip>
            </a-radio>
          <a-radio value="2">单图</a-radio>
        </a-radio-group>
        <p class="mt-10 fs-12">优质的封面有利于推荐，请使用清晰度较高的图片</p>
        <div class="mt-10" v-if="formRef.poster_access == '1'">
          <a-image :src="formRef.poster" v-if="formRef.poster" style="width: 104px;height: 104px;"/>
        </div>
        <div class="mt-10" v-else>
          <a-upload
            :action="$utils.imgAction"
            :headers="{ 'org-token': $store.getters.token }"
            v-model:file-list="imageList"
            @change="handleLogoUpload"
            @preview="handlePreview"
            :multiple="true"
            name="image"
            :data="{ dir: 'work_ai' }"
            accept="image/*"
            list-type="picture-card"
          >
            <div v-if="!imageList.length">
              <PlusOutlined />
              <div>上传图片</div>
            </div>
          </a-upload>
        </div>
      </a-form-item>

      <a-form-item label="标题"  v-bind="validateInfos.title">
        <a-input :maxlength="20" v-model:value="formRef.title" placeholder="平台标题0-20字"/>
        <p class="mt-10 fs-12">若平台独立标题为空，将使用文章默认标题</p>
      </a-form-item>
      <a-form-item label="图片">
        <p class="fs-12">默认取前三十五张图片</p>
      </a-form-item>

      <a-form-item label="描述" name="text">
        <p class="mb-10 fs-12">若编辑器中文字超出1000则默认选取前1000个字</p>
        <a-textarea :maxlength="1000" v-model:value="formRef.text" :rows="4" placeholder="描述0-1000字"></a-textarea>
      </a-form-item>

      <a-form-item label="选择音乐">
        <a-input class="cursor-pointer music-input" :value="musicTitle" :maxlength="20" placeholder="点击选择音乐" @click="musicDrawerVisible = true" readonly>
          <template #suffix>
            <CloseOutlined  @click="onMusicSelected(null)"/>
          </template>
        </a-input>
      </a-form-item>

      <!-- <a-form-item label="关联位置或小程序或购物车">
        <a-input :maxlength="20" v-model:value="formRef.title" placeholder="点击选择音乐" />
      </a-form-item> -->

      <a-form-item label="话题">
        <a-select
          v-model:value="formRef.challenges"
          mode="tags"
          :open="false"
          :getPopupContainer="triggerNode => triggerNode.parentNode"
          @change="onChallengeChange"
        >
          <template #dropdownRender>
            <div></div>
          </template>
        </a-select>
        <div class="fs-12">
          您可添加5个标签，每个标签不可以超过10个字，按回车键确认
        </div>
      </a-form-item>

      <a-form-item label="允许他人保存图片">
        <a-radio-group v-model:value="formRef.download">
          <a-radio value="1">允许</a-radio>
          <a-radio value="0">不允许</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item label="谁可以看">
        <a-radio-group v-model:value="formRef.visibility_type">
          <a-radio value="0">公开</a-radio>
          <a-radio value="2">好友可见</a-radio>
          <a-radio value="1">自己可见</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item label="发布时间" required>
        <a-radio-group v-model:value="formRef.publish_type">
          <a-radio value="1">立即发布</a-radio>
          <a-radio value="2">定时发布</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item  v-if="formRef.publish_type == 2" v-bind="validateInfos.publish_time">
        <a-date-picker :disabledDate="disabledDate"  :disabled-time="disabledDateTime"  :show-time="{ format:'YYYY-MM-DD HH:mm' }" format="YYYY-MM-DD HH:mm" placeholder="请选择时间" @change="onTimeChange" />
      </a-form-item>
    </a-form>

    <DouyinMusicDrawer
      v-model:visible="musicDrawerVisible"
      :accountId="accountId"
      @selected="onMusicSelected"
    ></DouyinMusicDrawer>
    <a-modal :visible="previewVisible" :footer="null" @cancel="()=>previewVisible=false">
         <img alt="example" style="width: 100%" :src="previewImage" />
      </a-modal>
  </div> 
</template>
   
<script>
  import { defineComponent, reactive, ref, watch, computed, nextTick } from "vue"
  import { useVModel } from '@vueuse/core'
  import { Form } from "ant-design-vue"
  import { QuestionCircleOutlined, PlusOutlined, CloseOutlined } from '@ant-design/icons-vue'
  import DouyinMusicDrawer from '../drawers/douyinMusic.vue'
  import { useUpload } from "../../../hooks/upload"
  import utils from "@/common/utils/utils"
  import moment from 'moment'
  import _ from 'lodash'

  const formData = {
    poster_access: "1",
    poster: '',
    title: '',
    text: '',
    cover_img: [],
    challenges: [],
    download: "1",
    music_id: "",
    music_end_time: "",
    visibility_type: "0",
    publish_type: "1",
    publish_time: "",
  }

  export default defineComponent({
    name: "douyin",
    components: {
      QuestionCircleOutlined,
      PlusOutlined,
      DouyinMusicDrawer,
      CloseOutlined
    },
    formData,
    props: {
      visible: {
        type: Boolean,
        default: false,
      },
      formData:{
        type: Object,
        default: () => formData
      },
      accountId: {
        type: Number,
        required: true
      },
      title: {
        type: String,
        default: ''
      },
      content: {
        type: String,
        default: ''
      },
    },
    
    setup(props, context) {
      const formRef = useVModel(props, 'formData', context.emit)

      formRef.value.title = props.title
      let { text, images } = utils.parseRichText(props.content)

      formRef.value.text = text.trim()
      formRef.value.poster = _.first(images) || ''
      formRef.value.cover_img = _.take(images, 35)
      
      const useForm = Form.useForm
      let validate_time = () => {

        if (formRef.value.publish_type == 2 && !formRef.value.publish_time) {

          return Promise.reject('请选择发布时间');
        } else {
          return Promise.resolve();
        }
      }
      let validate_poster = async(_rule, value)=>{
        console.log(imageList.value,'imageList.value');
      if(imageList.value.length==0){
          return Promise.reject('请上传封面');
        }else{
          return Promise.resolve();
        }
      }
      const rules = reactive({
        poster: [
          { required: true, message: '封面图片为必选项', trigger: 'change', validator:validate_poster},
        ],
        title: [
          { required: true, message: '标题为必填项'},
        ],
        text: [
          { required: true, message: '描述为必填项', trigger: 'blur' },
        ],
        publish_time: [
         {
           required: true,
           validator: validate_time,
           trigger: 'change',
         }
       ],
      })

      const { resetFields, validate ,validateInfos} = useForm(formRef, rules)
      const { imageList, handleUpload: handleLogoUpload } = useUpload()
      const challengeInputVisible = ref(false)
      const selectMusic = ref()
      const musicDrawerVisible = ref(false)

      const onMusicSelected = (music) => {
        selectMusic.value = music
        
        if(music){
          formRef.value.music_id = music.id
          formRef.value.music_end_time = music.duration * 1000
        } else {
          formRef.value.music_id = ''
          formRef.value.music_end_time = ''
        }
      }

      const musicTitle = computed(() => {
        return selectMusic.value
          ? selectMusic.value.title + `(${selectMusic.value.author})`
          : ''
      })

      watch(() => formRef.value.poster_access, (poster_access) => {
        if(poster_access == '1'){
          imageList.value = []
          nextTick(() => {
            let { images } = utils.parseRichText(props.content)
            formRef.value.poster = _.first(images) || ''
          })
        } else {
          formRef.value.poster = ''
          validate(['poster'])
        }
      })

      watch(imageList, (list) => {
        if (list.length) {
          formRef.value.poster = list[0].url
        } else {
          formRef.value.poster = ""
        }
      }, { deep: true })

      watch(() => props.title, (newTitle, oldTitle) => {
        if(! formRef.value.title || formRef.value.title == oldTitle){
          formRef.value.title = props.title
        }
      })

      watch(() => props.content, (newText, oldText) => {
        let { text, images } = utils.parseRichText(props.content)

        if(! formRef.value.text || formRef.value.text == oldText){
          formRef.value.text = text.trim()
        }

        if(formRef.value.poster_access == '1'){
          formRef.value.poster = _.first(images) || ''
        }

        formRef.value.cover_img = _.take(images, 35)
      })

      watch(() => formRef.value.publish_type, publish_type => {
        if(publish_type == '1'){
          formRef.value.publish_time = ''
        }else{
          validate(['publish_time'])
        }
      })

      const onChallengeChange = (values) => {
        formRef.value.challenges = _.take(values.filter(value => value.length <= 10), 5)
      }

      const onTimeChange = (e)=>{
        formRef.value.publish_time = e?moment(e).format('YYYY-MM-DD HH:mm'):null
      }
      const disabledDate= (current)=>{
        // 时间组件当前日期之前的日期不能选择
        return current && current < moment().startOf('day')
      }
      const disabledDateTime = (choosTime) => {
      let currentHour = moment().hour()
      let currentMinute = moment().minute()
    
      let disabledMinutes =  () => []
      let disabledHours = ()=>[]
      if(choosTime){
        disabledMinutes = moment(choosTime)>moment()?
       () => []:
       () => Array.from({ length: 61 }, (_, index) => index).splice(0, currentMinute + 1)

       disabledHours = moment(choosTime)>moment()?() => []:
       () => Array.from({ length: 25 }, (_, index) => index).splice(0, currentHour)
      }

      return {
        disabledHours,
        disabledMinutes,

      };
    }
      let previewVisible = ref(false)
      let previewImage = ref('')
      const handlePreview = async (file )=>{
          if (!file.url && !file.preview) {
          file.preview = await getBase64(file.originFileObj);
        }
        previewImage.value = file.url || file.preview;
        previewVisible.value = true;
      }
      const getBase64 = (file)=>{
        return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result);
        reader.onerror = error => reject(error);
         });
      }
      return {
        rules,
        formRef,
        imageList,
        handleLogoUpload,
        challengeInputVisible,
        onMusicSelected,
        musicDrawerVisible,
        selectMusic,
        musicTitle,
        onChallengeChange,
        onTimeChange,
        validate,
        validateInfos,
        disabledDate,
        disabledDateTime,
        previewVisible,
        previewImage,
        handlePreview,
      };
    },
  });
</script>
   
   <style lang="less">
      .music-input input {
        cursor: pointer;
      }
      .ss-form-item-has-error  .ss-upload{
       background-color: #fff!important;
       border-color: #ff4d4f!important;
     }  
   </style>
   